// ** React Imports
import { useState, Fragment, useEffect } from 'react'

// ** Reactstrap Imports
import {
  Card,
  CardHeader,
  CardTitle,
  CardBody,
  Button,
  ListGroup,
  ListGroupItem,
} from 'reactstrap'

import { PreviewUrl } from '../../../configs/server'
import { uploadFile } from '../../../api/activity'
// ** Third Party Imports
import { useDropzone } from 'react-dropzone'
import { FileText, X, DownloadCloud } from 'react-feather'

const FileUploaderSingle = ({
  onEditFileChange,
  filesId,
  disabled,
  type = 'image',
}) => {
  // ** State
  const [files, setFiles] = useState([])
  const [filesIdArr, setFilesIdArr] = useState([])

  useEffect(() => {
    if (filesId && filesId.length) {
      setFilesIdArr([...filesIdArr, ...filesId])
    }
  }, [filesId])

  useEffect(() => {
    onEditFileChange(filesIdArr)
  }, [filesIdArr])

  const { getRootProps, getInputProps } = useDropzone({
    multiple: false,
    onDrop: (acceptedFiles) => {
      const newFiles = [
        ...files,
        ...acceptedFiles.map((file) => Object.assign(file)),
      ]
      setFiles(newFiles)
      uploadFile(newFiles[0]).then((res) => {
        if (res.$id) {
          const newId = [...filesIdArr, res.$id]
          setFilesIdArr(newId)
        }
      })
    },
  })

  const picPreview = (id) => {
    return (
      <img className="rounded" src={PreviewUrl(id)} height="28" width="28" />
    )
  }
  const Video = (id) => {
    return (
      <div>
        <video controls>
          <source src={PreviewUrl(id)} type="video/mp4" />
          <source src={PreviewUrl(id)} type="video/webm" />
          <source src={PreviewUrl(id)} type="video/ogg" />
        </video>
      </div>
    )
  }
  const renderFilePreview = (file) => {
    if (file.type.startsWith('image')) {
      return (
        <img
          className="rounded"
          alt={file.name}
          src={URL.createObjectURL(file)}
          height="28"
          width="28"
        />
      )
    } else {
      return <FileText size="28" />
    }
  }

  const handleRemoveFile = (file) => {
    const filtered = filesIdArr.filter((i) => i !== file)
    setFilesIdArr([...filtered])
  }

  const renderFileSize = (size) => {
    if (Math.round(size / 100) / 10 > 1000) {
      return `${(Math.round(size / 100) / 10000).toFixed(1)} mb`
    } else {
      return `${(Math.round(size / 100) / 10).toFixed(1)} kb`
    }
  }

  const editFileList =
    filesIdArr.length &&
    filesIdArr.map((file) => (
      <ListGroupItem
        key={`${file}`}
        className="d-flex align-items-center justify-content-between"
      >
        <div className="file-details d-flex align-items-center">
          <div className="file-preview me-1">
            {type === 'video' ? Video(file) : picPreview(file)}
          </div>
        </div>
        {disabled ? null : (
          <Button
            color="danger"
            outline
            size="sm"
            className="btn-icon"
            onClick={() => handleRemoveFile(file)}
          >
            <X size={14} />
          </Button>
        )}
      </ListGroupItem>
    ))

  return (
    <Card>
      <CardHeader></CardHeader>
      <CardBody>
        {disabled ? null : (
          <div {...getRootProps({ className: 'dropzone' })}>
            <input {...getInputProps()} />
            <div className="d-flex align-items-center justify-content-center flex-column">
              <DownloadCloud size={64} />
              <p className="text-secondary">点击或拖拽上传</p>
            </div>
          </div>
        )}
        {filesIdArr.length ? (
          <Fragment>
            <ListGroup className="my-2">{editFileList}</ListGroup>
            <div className="d-flex justify-content-end"></div>
          </Fragment>
        ) : null}
      </CardBody>
    </Card>
  )
}

export default FileUploaderSingle
